package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.domain.airfreight.AbstractPlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.TransitEntity;
import com.foreveross.crawl.domain.airfreight.doub.DoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnCabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnTransitEntity;
import com.foreveross.crawl.util.DateUtil;
import com.foreveross.crawl.util.StringUtil;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.sun.jersey.api.MessageException;

public class KoreanAirAdapter_bak_2  extends AbstractAdapter{

	public KoreanAirAdapter_bak_2(TaskModel taskQueue) {
		super(taskQueue);
	}
	private static final String cnHomeUrl = "http://www.koreanair.com/index_cn_chn.jsp";
	private static final String tranUrl = "http://www.koreanair.com/global/bl/rs/rs_v9reservationController.jsp";

	private Map<String,String>sourceByID=Maps.newHashMap();//ID下对应的详细信息
	
	
	private Map<String,String> familyButtonParmaMap=Maps.newHashMap();
	private String url;
	private String jsessionID;
	private int Tip=3;//失败再执行次数
	
	
	private List<String> FgRows=Lists.newArrayList();
	private List<String> FrRows=Lists.newArrayList();
	

	private Map<String,String>priceMap=Maps.newHashMap();//对应舱位下最低价
	private Map<String,String>priceFamilyB=Maps.newHashMap();//最低价对就的参数信息
	private Map<String ,Map<String,List<String>>> allDatas=Maps.newHashMap();//存储所有抓取到的页面信息
//	private Map<String,String>taxCabin=Maps.newHashMap();//舱位对应的税价
	private Map<String,String> canbIdPrice=Maps.newHashMap();//对应舱位下对应ID的价格
	private Map<String,String> priceCanbinName=Maps.newHashMap();//价格对应的舱位商品名
	
	
	//舱位
	private static final Map<String,String> cabins = new LinkedHashMap<String, String>();
	{
		cabins.put("ECOSPCL1", "经济舱特价");
		cabins.put("ECONOMY1", "经济舱");
		cabins.put("PRESTIGE1", "商务舱");
//		cabins.put("F", "头等舱");
	}
	
	
	@Override
	public Object fetch(String arg0) throws Exception {
		switch (super.getRouteType()) {
		case INTERNATIONAL_ROUND:
			return fetchDI();//国际往返
		}
		return null;
	}
	
	
	/**
	 * fetchDI();
	 * 国际往返
	 */
	public Object fetchDI() throws Exception {
		List<String> objs=Lists.newArrayList();
		HttpPost httpPost = null;
		HttpGet g=null;
		HttpClient httpClient = this.getHttpClient();
		String page1="",page2="",page3="";
		Map<String,String> flightParams = Maps.newHashMap();
		Map<String,String> tranParams = null;
		Document doc;
		HttpResponse reponse=null;
		HttpEntity entity =null;
		try{
			//处理经济+商务舱信息
			for(String cabinType:cabins.keySet()){
				logger.info("【"+cabins.get(cabinType)+"】进入第首页...");
				g= new HttpGet(cnHomeUrl);
				reponse=httpClient.execute(g);
				entity = reponse.getEntity();
				EntityUtils.consume(entity);//释放掉Response中的IO资源
				
				logger.info("【"+cabins.get(cabinType)+"】进入第二层...");
				httpPost = new HttpPost(F_URL(cabinType));
				setPostHeadInfo(httpPost,cnHomeUrl,"www.koreanair.com");
				reponse = httpClient.execute(httpPost);
				entity = reponse.getEntity();
				EntityUtils.consume(entity);//释放掉Response中的IO资源
				
				logger.info("【"+cabins.get(cabinType)+"】进入第三层...");
				httpPost=new HttpPost(S_URL(cabinType));
				setPostHeadInfo(httpPost,tranUrl,"www.koreanair.com");
				reponse = httpClient.execute(httpPost);
				entity = reponse.getEntity();
				page1=EntityUtils.toString(entity,"GBK");
				if(page1 !=null && page1.contains("The URL has moved ")){
					logger.info("IP被封,");
					while(Tip-->0){
						logger.info(String.format("尝试倒数第%s次",Tip));
						fetchDI();
					}
				}
//				page1=excuteRequest(httpClient, httpPost, "UTF-8");
				if(page1.contains("ENC") ){
					doc = Jsoup.parse(page1);
					Element enc = doc.select("input[name=ENC]").first();
//					Element transAction=doc.select("input[name=EMBEDDED_TRANSACTION]").first();
					flightParams.put("ENC", enc.val());
//					flightParams.put("EMBEDDED_TRANSACTION",transAction.val());
					flightParams.put("COMMERCIAL_FARE_FAMILY_1",cabinType);
					
					EntityUtils.consume(entity);//释放掉Response中的IO资源
					if(flightParams.get("ENC") !=null){
						logger.info("【"+cabins.get(cabinType)+"】进入第四层，获取对航班信息...");
						httpPost=new HttpPost(T_URL(cabinType,flightParams));
						setPostHeadInfo(httpPost,"http://www.koreanair.com/local/cn/ld/sch/tp/bo/sch_tp_bo_ifr.jsp","wftc3.e-travel.com");
						reponse = httpClient.execute(httpPost);
						entity = reponse.getEntity();
						page2=EntityUtils.toString(entity,"GBK");
						Map<String,Map<Set<String>,Set<String>>> infoMaps=Maps.newHashMap();
						if(page2 !=null){;
						
					/*	if(cabinType.equals("F")){// 头等舱单独请求	
							Map<String, List<String>> Fdatas=Maps.newHashMap();
							List<String> datasList=Lists.newArrayList();
							 Element form = Jsoup.parse(page2).getElementById("FlightDetailsPopUpForm");;
							 String urls = form.attr("action");
							String Furl = urls.startsWith("http")? url : "https://wftc3.e-travel.com" + url;
							
							getPatternList(page2,"<td\\s*id=\"tdRadioBtIndex_1_(\\d*)"," ","");
							
							EntityUtils.consume(entity);//释放掉Response中的IO资源
							
							if(FgRows.size()>0&& FrRows.size()>0){
								for(String row1:FgRows){
									for(String row2:FrRows){
										httpPost=getBasePost(Furl, getFPa(row1, row2));
										setPostHeadInfo(httpPost,"http://wftc3.e-travel.com/plnext/KEREG/Override.action","wftc3.e-travel.com");
										reponse = httpClient.execute(httpPost);
										entity = reponse.getEntity();
										if(entity ==null )continue;
										String pageF="";
										pageF=EntityUtils.toString(entity, "GBK");
										datasList.add(pageF);
									//	Fdatas.put("1", pageF);
										//getFPa
										allDatas.put(cabinType, Fdatas);
									}
								}
							
							
							}
							continue;
						}
						
						*/
							logger.info("解析页面对应的信息。。。");
							Tr_Page(page2,infoMaps,familyButtonParmaMap,cabinType);
						}
						
						EntityUtils.consume(entity);//释放掉Response中的IO资源
						
						
						
						if (infoMaps.size() > 0 && familyButtonParmaMap.size()>0 && priceFamilyB.size()>0) {
							logger.info("【" + cabins.get(cabinType)+ "】进入第五层，获取对应的航班信息！");
							//取出所有的
							for (Map.Entry<String, Map<Set<String>, Set<String>>> infoMap : infoMaps.entrySet()) {
								String s1 = infoMap.getKey();
								Map<Set<String>, Set<String>> infoLists = infoMap.getValue();
							
								//取出最低价
//								String s1 = priceFamilyB.get(priceMap.get(cabinType)+"0");
//								Map<Set<String>, Set<String>> infoLists = infoMaps.get(s1);
								
								for (Map.Entry<Set<String>, Set<String>> infoList : infoLists.entrySet()) {
									for (String s2 : infoList.getKey()) {
										for (String s3 : infoList.getValue()) {
										 if(familyButtonParmaMap.get(s1) ==null) continue;
										 
										 
											if(priceCanbinName.size()>0){
												//过滤出已经抓取过的航班信息//Map<String, Map<String, List<String>>> 
												if(sourceByID.get(s2+"-"+s3) !=null) {
													if(allDatas.get(cabinType) !=null){
														if(allDatas.get(cabinType).get(s1) !=null){
															allDatas.get(cabinType).get(s1).add(sourceByID.get(s2+"-"+s3));
														}else{
															List<String> getStrList=Lists.newArrayList();
															getStrList.add(sourceByID.get(s2+"-"+s3) );
															allDatas.get(cabinType).put(s1, getStrList);
														}
														continue;
													}
													
												}
											}
											
											
											httpPost=getBasePost(url, getPa(familyButtonParmaMap.get(s1), s2, s3));
//											httpPost = new HttpPost(getLastUrl(familyButtonParmaMap.get(s1), s2, s3, jsessionID));
											setPostHeadInfo(httpPost,"http://wftc3.e-travel.com/plnext/KEREG/Override.action","wftc3.e-travel.com");
											reponse = httpClient.execute(httpPost);
											entity = reponse.getEntity();
											if(entity ==null )continue;
											page3 = EntityUtils.toString(entity, "GBK");
//											page3=excuteRequest(httpClient, httpPost, "UTF-8");
											logger.info(".....数据获取成功.....");
											
											//存入过滤容器中
											sourceByID.put(s2+"-"+s3, page3);
											
											//Map<String, Map<String, List<String>>> 
											if(allDatas.get(cabinType) !=null){
												if(allDatas.get(cabinType).get(s1)!=null){
													allDatas.get(cabinType).get(s1).add(page3);
												}else{
													List<String> getStrList=Lists.newArrayList();
													getStrList.add(page3);
													allDatas.get(cabinType).put(s1, getStrList);
												}
											}else{
												Map<String,List<String>> priceDataL=Maps.newHashMap();
												List<String> getStrList=Lists.newArrayList();
												getStrList.add(page3);
												priceDataL.put(s1, getStrList);
												allDatas.put(cabinType,priceDataL);
											}
										}
									}
								}
							}
						}
					}
				}
			}
				
				
//			}
			
			//单独处理头等舱信息
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return objs;
	}
	
	
	
	
	
	/**
	 * 设置请求头信息
	 * @param get
	 */
	private void setRequestHeadInfo(HttpRequestBase g) {
		g.setHeader("Host", "book.aircanada.com");
		g.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/31.0");
		g.setHeader("Accept","	text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		g.setHeader("Referer", "http://www.aircanada.com/zh/home.html");
		g.setHeader("Accept-Language", "zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3");
	}
	
	/**
	 * 设置请求头信息
	 * @param post
	 */
	private void setPostHeadInfo(HttpPost httpPost,String postUrl,String host) {
		httpPost.setHeader("Host", host);
		httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0");
		httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
		httpPost.setHeader("Referer",postUrl);
	}
	
	/**
	 * 解析页面，获取对应的参数信息
	 * @return
	 */
	public void Tr_Page(String page,Map<String,Map<Set<String>,Set<String>>>infoMaps,Map<String,String>familyButtonParmaMap,String cabinType){
		
		 Elements priceInputEls = Jsoup.parse(page).select("td[id^=FRB_] input[type=radio]");
		if(priceInputEls.size()>0){
			 for(Element priceInput : priceInputEls){
				String familyId_H=priceInput.attr("value");
				String onclick = priceInput.attr("onclick");
				String selectedRecommendationID  = RegHtmlUtil.regStr(onclick,"FRB_(.*)\'").replace("_", "|");
				familyButtonParmaMap.put(selectedRecommendationID,familyId_H);
			}
		}
		
		//获取页面上所有的价格
		Set<String>priceSet=Sets.newHashSet();
		Elements priceValue = Jsoup.parse(page).select("td[id^=FRB_]");
		if(priceValue.size()>0){
			for(Element price : priceValue){
				String priceStr= RegHtmlUtil.regStr(price.text().replaceAll(",",""), "([0-9]*\\.?[0-9]{1,2})");
				priceSet.add(priceStr);
			}
		}
		
		//解析出对应价格下对应的舱位类型
		Element priceTAB=Jsoup.parse(page).select("table[class=fdff_tableFF]").first();
		if(priceTAB !=null ){
			String TABstr=RegHtmlUtil.regStr(priceTAB.toString(), "(<tr\\s*class=\"\\w*?\\W*?\".*</tr>)");
			Element TABel=Jsoup.parse("<html><body><table>"+TABstr+"</table></body></html>");
			Elements trEls=TABel.getElementsByTag("tr");
			for(Element trEL:trEls){
				String cabName=trEL.select("td:eq(1)").text();
				for(int i=3;i<trEL.getElementsByTag("td").size();i++){
					String priceStr=trEL.select("td:eq("+i+")").text().replaceAll(",", "").replaceAll(" ", "").substring(1).replaceAll("Ұ", "");
					priceCanbinName.put(priceStr, cabName);
				}
			}
		}
		
		
		/**
		 * 最后一层URL
		 */
		 Element fdff_form = Jsoup.parse(page).getElementById("FDFF_FORM");
		 url = fdff_form.attr("action");
		
		Element priceInputs = Jsoup.parse(page).select("form[name=FDFF_FORM]").first();
		if(jsessionID==null || jsessionID==""){
			jsessionID=RegHtmlUtil.regStr(priceInputs.toString(),"jsessionid=(.*)\"\\s*method");
		}
		String jsonStr=RegHtmlUtil.regStr(page,"var\\s*generatedJSon\\s*=\\s*new\\s*String\\(\'(\\{.*\\})\'");
		JSONObject json=JSONObject.fromObject(jsonStr);
		//解析JSON
		JSONObject JA=new JSONObject();
		JA=json.getJSONObject("listRecos");
		if(JA.size()>0){
			Iterator jo=JA.entrySet().iterator();
			while(jo.hasNext()){
				JSONObject dJso	=JSONObject.fromObject(jo.next());
				JSONObject lJso=JSONObject.fromObject(dJso.getString("value"));
				String priceStr=lJso.getJSONObject("price").getString("price");
				JSONArray outAr=lJso.getJSONArray("outboundFlights");
				JSONArray inAr=lJso.getJSONArray("inboundFlights");
				String familyId=lJso.getString("familyID");
				if(priceStr !=null){
					priceStr=RegHtmlUtil.regStr(StringUtil.unicodeToUtf8(priceStr).replaceAll(",",""), "([0-9]*\\.?[0-9]{1,2})");//Ұ13,557.00
					priceFamilyB.put(priceStr, familyId);
					canbIdPrice.put(familyId, priceStr);
				}
				Map<Set<String>,Set<String>> mapLists=Maps.newHashMap();
				if(outAr.size()>0 && inAr.size()>0){
					Set<String> inA=Sets.newHashSet();
					Set<String> outA=Sets.newHashSet();
					for(int j=0;j<outAr.size();j++){
						if(!outAr.get(j).equals("null")&& outAr.get(j)!=null){
							String outMap[]=outAr.get(j).toString().split("|");
							for(String t:outMap){
								if(t.matches("\\d+")){//判断是不是纯数字
									outA.add(t);
								}
							}
						}
					}
					
					for(int k=0;k<inAr.size();k++){
						if(!inAr.get(k).equals("null")&&inAr.get(k) !=null){
							String inMap[]=inAr.get(k).toString().split("|");
							for(String t:inMap){
								if(t.matches("\\d+")){//判断是不是纯数字
									inA.add(t);
								}
							}
						}
					}
					
					if(inA.size()>0 && outA.size()>0)mapLists.put(outA, inA);
				}
				
				if(mapLists.size()>0) infoMaps.put(familyId, mapLists);
			}
			
			//获取页面最低价
			if(priceSet.size()>0 && priceList(priceSet) !=null && !priceList(priceSet).equals("")){//排序最低价
				priceMap.put(cabinType, priceList(priceSet));
			}
		}
	}
	
	/**
	 * 排序最低价
	 * @return 
	 */
	public String priceList(Set<String>priceStr){
		Double lowerPrices=9999999999.0d;
		Iterator<String> it = priceStr.iterator(); 
		while(it.hasNext()){
			String price=it.next();
			if(Double.parseDouble(price)<lowerPrices){
				lowerPrices=Double.parseDouble(price);
			}
		}
		return lowerPrices+"";
	}
	
	
	private List<String> getPatternList(String content, String regEx, String replace, String replacement){
		Pattern p=Pattern.compile(regEx, Pattern.DOTALL|Pattern.MULTILINE);
		Matcher m=p.matcher(content);
		List<String> strList = new ArrayList<String>();
		while(m.find()){
			strList.add(m.group(1).trim().replaceAll(replace, replacement));
		}
		return strList;
	}
	
	
	/**
	 * 第二层
	 * @return
	 */
	public String F_URL(String cabinType){
		String[] goDate = taskQueue.getFlightDate().split("-");
		String[] returnDate = taskQueue.getReturnGrabDate().split("-");
		StringBuffer url=new StringBuffer("http://www.koreanair.com/global/bl/rs/rs_v9reservationController.jsp?");
		url.append("AIRLINE_1_1=KE");
		url.append("&");
		url.append("ARRANGE_BY=N");
		url.append("&");
		url.append("B_ANY_TIME_1=TURE");
		url.append("&");
		url.append("B_ANY_TIME_2=TURE");
		url.append("&");
		url.append("B_DATE_1="+getRequestDate(taskQueue.getFlightDate()));
		url.append("&");
		url.append("B_DATE_2="+getRequestDate(taskQueue.getReturnGrabDate()));
		url.append("&");
		url.append("B_DAY="+goDate[2]);
		url.append("&");
		url.append("B_LOCATION_1="+taskQueue.getFromCity());
		url.append("&");
		url.append("B_MONTH="+goDate[0] + goDate[1]);
		url.append("&");
		url.append("B_REG_ID=CHN");//出发国家
		url.append("&");
		url.append("B_TIME=0000");
		url.append("&");
		url.append("CABIN=");
		url.append("&");
		url.append("COMMERCIAL_FARE_FAMILY_1="+cabinType);
		url.append("&");
		url.append("DATE_RANGE_VALUE_1=0");
		url.append("&");
		url.append("DIRECT_LOGIN=NO");
		url.append("&");
		url.append("EXTERNAL_ID=KE");
		url.append("&");
		url.append("E_DAY="+returnDate[2]);
		url.append("&");
		url.append("E_LOCATION_1="+taskQueue.getToCity());
		url.append("&");
		url.append("E_MONTH="+returnDate[0] + returnDate[1]);
		url.append("&");
		url.append("E_REG_ID=USA");//到达国家
		url.append("&");
		url.append("E_TIME=0000");
		url.append("&");
		url.append("H_Site=CN");
		url.append("&");
		url.append("LANGUAGE=CN");
		url.append("&");
		url.append("SERVLET_NAME_KEY=FlexPricerAvailability");
		url.append("&");
		url.append("SESSION_ID=");
		url.append("&");
		url.append("SEVEN_DAY_SEARCH=TRUE");
		url.append("&");
		url.append("SITE=CAUOCAUO");
		url.append("&");
		url.append("SO_SITE_FP_BACKUP_TO_CAL=TRUE");
		url.append("&");
		url.append("TRAVELLER_TYPE=1");
		url.append("&");
		url.append("TRAVELLER_TYPE_1=ADT");
		url.append("&");
		url.append("TRAVELLER_TYPE_2=");
		url.append("&");
		url.append("TRAVELLER_TYPE_3=");
		url.append("&");
		url.append("TRAVELLER_TYPE_4=");
		url.append("&");
		url.append("TRAVELLER_TYPE_5=");
		url.append("&");
		url.append("TRAVELLER_TYPE_6=");
		url.append("&");
		url.append("TRAVELLER_TYPE_7=");
		url.append("&");
		url.append("TRAVELLER_TYPE_8=");
		url.append("&");
		url.append("TRAVELLER_TYPE_9=");
		url.append("&");
		url.append("TRIP_TYPE="+getTripType());
		url.append("&");
		url.append("T_Site=CAUOCAUO");
		url.append("&");
		url.append("agentCode=QEC");
		url.append("&");
		url.append("date_range=on");
		url.append("&");
		url.append("homeLoginPageName="+URLEncoder.encode("/")+"index_cn_chn.jsp");
		url.append("&");
		url.append("lateLoginPageName="+URLEncoder.encode("/")+"local"+URLEncoder.encode("/")+"cn"+URLEncoder.encode("/")+"ld"+URLEncoder.encode("/")+"sch"+URLEncoder.encode("/")+"ft"+URLEncoder.encode("/")+"mb"+URLEncoder.encode("/")+"mp_signIn_guest.jsp");
		url.append("&");
		url.append("ownerCode=QEC");
		url.append("&");
		url.append("selectedYYYY=");
		url.append("&");
		url.append("selectedYYYY2=");
		url.append("&");
		url.append("serverName=www.koreanair.com");
		url.append("&");
		url.append("system=kihe");
		url.append("&");
		url.append("topasURL=http"+URLEncoder.encode("://")+"www.koreanair.com"+URLEncoder.encode("/")+"local"+URLEncoder.encode("/")+"cn"+URLEncoder.encode("/")+"ld"+URLEncoder.encode("/")+"sch"+URLEncoder.encode("/")+"tp"+URLEncoder.encode("/")+"bo"+URLEncoder.encode("/")+"sch_tp_bo_ifr.jsp");
		url.append("&");
		url.append("v7ResURL=http"+URLEncoder.encode("://")+"wftc3.e-travel.com"+URLEncoder.encode("/")+"plnext"+URLEncoder.encode("/")+"KEREG"+URLEncoder.encode("/")+"Override.action");
		return url.toString();
	}
	
	/**
	 * 第三层URL
	 * @return
	 */
	public String S_URL(String cabinType){
		StringBuffer url=new StringBuffer("http://www.koreanair.com/global/bl/rs/tripflow_log_enct_xwkc.jsp?");
		url.append("ARRANGE_BY=E");
		url.append("&");
		url.append("B_ANY_TIME_1=TRUE");
		url.append("&");
		url.append("B_ANY_TIME_2=TRUE");
		url.append("&");
		url.append("B_DATE_1="+getRequestDate(taskQueue.getFlightDate()));
		url.append("&");
		url.append("B_DATE_2="+getRequestDate(taskQueue.getReturnGrabDate()));
		url.append("&");
		url.append("B_LOCATION_1="+taskQueue.getFromCity());
		url.append("&");
		url.append("CABIN=");
		url.append("&");
		url.append("COMMERCIAL_FARE_FAMILY_1="+cabinType);
		url.append("&");
		url.append("DATE_RANGE_QUALIFIER_1=C");
		url.append("&");
		url.append("DATE_RANGE_QUALIFIER_2=C");
		url.append("&");
		url.append("DATE_RANGE_VALUE_1=0");
		url.append("&");
		url.append("DATE_RANGE_VALUE_2=0");
		url.append("&");
		url.append("DIRECT_LOGIN=NO");
		url.append("&");
		url.append("DISPLAY_TYPE=2");
		url.append("&");
		url.append("EMBEDDED_TRANSACTION=FlexPricerAvailability");
		url.append("&");
		url.append("ENCT=1");
		url.append("&");
		url.append("EXTERNAL_ID=QEC");
		url.append("&");
		url.append("EXTERNAL_ID=QEC");
		url.append("&");
		url.append("E_LOCATION_1="+taskQueue.getToCity());
		url.append("&");
		url.append("FIELD_ADT_NUMBER=1");
		url.append("&");
		url.append("FIELD_CHD_NUMBER=0");
		url.append("&");
		url.append("FIELD_INFANTS_NUMBER=0");
		url.append("&");
		url.append("HAS_INFANT_1=");
		url.append("&");
		url.append("HAS_INFANT_2=");
		url.append("&");
		url.append("HAS_INFANT_3=");
		url.append("&");
		url.append("HAS_INFANT_4=");
		url.append("&");
		url.append("HAS_INFANT_5=");
		url.append("&");
		url.append("HAS_INFANT_6=");
		url.append("&");
		url.append("HAS_INFANT_7=");
		url.append("&");
		url.append("HAS_INFANT_8=");
		url.append("&");
		url.append("HAS_INFANT_9=");
		url.append("&");
		url.append("H_Site=CN");
		url.append("&");
		url.append("LANGUAGE=CN");
		url.append("&");
		url.append("PRICING_TYPE=I");
		url.append("&");
		url.append("SEARCH_PAGE=SD");
		url.append("&");
		url.append("SESSION_ID=");
		url.append("&");
		url.append("SEVEN_DAY_SEARCH=TRUE");
		url.append("&");
		url.append("SITE=CAUOCAUO");
		url.append("&");
		url.append("SO_GL=");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE1=Korean%20Air%20China%20Service%20Center(Qingdao)");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE2=TEL)%2086-40065-88888");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE3=");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE4=");
		url.append("&");
		url.append("SO_LANG_SITE_EMAIL_ADDRESS=chinaservicecenter"+URLEncoder.encode("@")+"koreanair.com");
		url.append("&");
		url.append("SO_QUEUE_OFFICE_ID=SELKE1200");
		url.append("&");
		url.append("SO_SITE_CLASS_OF_SERVICE=in%20availability%20page");
		url.append("&");
		url.append("SO_SITE_CMP_DATE_IN_GMT=TRUE");
		url.append("&");
		url.append("SO_SITE_EXT_PSPURL=https"+URLEncoder.encode("://")+"cyb.koreanair.com"+URLEncoder.encode("/")+"iKalApp"+URLEncoder.encode("/")+"cn"+URLEncoder.encode("/")+"int"+URLEncoder.encode("/")+"purchase"+URLEncoder.encode("/")+"chn_paymentProcess.jsp");
		url.append("&");
		url.append("SO_SITE_FORCE_DDAY_AVAIL=TRUE");
		url.append("&");
		url.append("SO_SITE_FP_BACKUP_TO_CAL=TRUE");
		url.append("&");
		url.append("SO_SITE_MAIL_FROM=chinaservicecenter"+URLEncoder.encode("@")+"koreanair.com");
		url.append("&");
		url.append("SO_SITE_MAIL_REPLY_TO=chinaservicecenter"+URLEncoder.encode("@")+"koreanair.com");
		url.append("&");
		url.append("SO_SITE_MOD_DELIVERY=FALSE");
		url.append("&");
		url.append("SO_SITE_MOP_CREDIT_CARD=FALSE");
		url.append("&");
		url.append("SO_SITE_MOP_EXT=TRUE");
		url.append("&");
		url.append("SO_SITE_OFFICE_ID=LAXKE18CC");
		url.append("&");
		url.append("SO_SITE_POINT_OF_SALE=BJS");
		url.append("&");
		url.append("SO_SITE_POINT_OF_TICKETING=BJS");
		url.append("&");
		url.append("TRAVELLER_TYPE_1=ADT");
		url.append("&");
		url.append("TRAVELLER_TYPE_2=");
		url.append("&");
		url.append("TRAVELLER_TYPE_3=");
		url.append("&");
		url.append("TRAVELLER_TYPE_4=");
		url.append("&");
		url.append("TRAVELLER_TYPE_5=");
		url.append("&");
		url.append("TRAVELLER_TYPE_6=");
		url.append("&");
		url.append("TRAVELLER_TYPE_7=");
		url.append("&");
		url.append("TRAVELLER_TYPE_8=");
		url.append("&");
		url.append("TRAVELLER_TYPE_9=");
		url.append("&");
		url.append("TRIP_TYPE="+getTripType());
		url.append("&");
		url.append("actionURL=http"+URLEncoder.encode("://")+"www.koreanair.com"+URLEncoder.encode("/")+"local"+URLEncoder.encode("/")+"cn"+URLEncoder.encode("/")+"ld"+URLEncoder.encode("/")+"sch"+URLEncoder.encode("/")+"tp"+URLEncoder.encode("/")+"bo"+URLEncoder.encode("/")+"sch_tp_bo_ifr.jsp");
		url.append("&");
		url.append("agentCode=QEC");
		url.append("&");
		url.append("gweb_kal=rkddnjstlr");
		url.append("&");
		url.append("v7ResURL=http"+URLEncoder.encode("://")+"wftc3.e-travel.com"+URLEncoder.encode("/")+"plnext"+URLEncoder.encode("/")+"KEREG"+URLEncoder.encode("/")+"Override.action");
		
		return url.toString();
	}
	
	/**
	 * 第四层，获取对应的航班信息
	 * @return
	 */
	public String T_URL(String cabinType,Map<String, String>flightParams){
		StringBuffer url=new StringBuffer("http://wftc3.e-travel.com/plnext/KEREG/Override.action?");
		url.append("ARRANGE_BY=E");
		url.append("&");
		url.append("B_ANY_TIME_1=TRUE");
		url.append("&");
		url.append("B_ANY_TIME_2=TRUE");
		url.append("&");
		url.append("CABIN=");
		url.append("&");
		url.append("COMMERCIAL_FARE_FAMILY_1="+cabinType);
		url.append("&");
		url.append("DATE_RANGE_QUALIFIER_1=C");
		url.append("&");
		url.append("DATE_RANGE_QUALIFIER_2=C");
		url.append("&");
		url.append("DATE_RANGE_VALUE_1=0");
		url.append("&");
		url.append("DATE_RANGE_VALUE_2=0");
		url.append("&");
		url.append("DIRECT_LOGIN=NO");
		url.append("&");
		url.append("DISPLAY_TYPE=2");
		url.append("&");
		url.append("EMBEDDED_TRANSACTION=FlexPricerAvailability");
		url.append("&");
		url.append("ENC="+flightParams.get("ENC"));
		url.append("&");
		url.append("ENCT=1");
		url.append("&");
		url.append("EXTERNAL_ID=QEC");
		url.append("&");
		url.append("FIELD_ADT_NUMBER=0");
		url.append("&");
		url.append("FIELD_CHD_NUMBER=0");
		url.append("&");
		url.append("FIELD_INFANTS_NUMBER=0");
		url.append("&");
		url.append("HAS_INFANT_1=");
		url.append("&");
		url.append("HAS_INFANT_2=");
		url.append("&");
		url.append("HAS_INFANT_3=");
		url.append("&");
		url.append("HAS_INFANT_4=");
		url.append("&");
		url.append("HAS_INFANT_5=");
		url.append("&");
		url.append("HAS_INFANT_6=");
		url.append("&");
		url.append("HAS_INFANT_7=");
		url.append("&");
		url.append("HAS_INFANT_8=");
		url.append("&");
		url.append("HAS_INFANT_9=");
		url.append("&");
		url.append("H_Site=CN");
		url.append("&");
		url.append("LANGUAGE=CN");
		url.append("&");
		url.append("PRICING_TYPE=I");
		url.append("&");
		url.append("SEARCH_PAGE=SD");
		url.append("&");
		url.append("SESSION_ID=");
		url.append("&");
		url.append("SEVEN_DAY_SEARCH=TRUE");
		url.append("&");
		url.append("SITE=CAUOCAUO");
		url.append("&");
		url.append("SO_GL=");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE1=Korean%20Air%20China%20Service%20Center(Qingdao)");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE2=TEL)%2086-40065-88888");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE3=");
		url.append("&");
		url.append("SO_LANG_SITE_AGENCY_LINE4=");
		url.append("&");
		url.append("SO_LANG_SITE_EMAIL_ADDRESS=chinaservicecenter"+URLEncoder.encode("@")+"koreanair.com");
		url.append("&");
		url.append("SO_QUEUE_OFFICE_ID=SELKE1200");
		url.append("&");
		url.append("SO_SITE_CLASS_OF_SERVICE=in%20availability%20page");
		url.append("&");
		url.append("SO_SITE_EXT_PSPURL=https"+URLEncoder.encode("://")+"cyb.koreanair.com"+URLEncoder.encode("/")+"iKalApp"+URLEncoder.encode("/")+"cn"+URLEncoder.encode("/")+"int"+URLEncoder.encode("/")+"purchase"+URLEncoder.encode("/")+"chn_paymentProcess.jsp");
		url.append("&");
		url.append("SO_SITE_FORCE_DDAY_AVAIL=TRUE");
		url.append("&");
		url.append("SO_SITE_FP_BACKUP_TO_CAL=TRUE");
		url.append("&");
		url.append("SO_SITE_MAIL_FROM=chinaservicecenter"+URLEncoder.encode("@")+"koreanair.com");
		url.append("&");
		url.append("SO_SITE_MAIL_REPLY_TO=chinaservicecenter"+URLEncoder.encode("@")+"koreanair.com");
		url.append("&");
		url.append("SO_SITE_MOD_DELIVERY=FALSE");
		url.append("&");
		url.append("TRAVELLER_TYPE_1=");
		url.append("&");
		url.append("TRAVELLER_TYPE_2=");
		url.append("&");
		url.append("TRAVELLER_TYPE_3=");
		url.append("&");
		url.append("TRAVELLER_TYPE_4=");
		url.append("&");
		url.append("TRAVELLER_TYPE_5=");
		url.append("&");
		url.append("TRAVELLER_TYPE_6=");
		url.append("&");
		url.append("TRAVELLER_TYPE_7=");
		url.append("&");
		url.append("TRAVELLER_TYPE_8=");
		url.append("&");
		url.append("TRAVELLER_TYPE_9=");
		url.append("&");
		url.append("TRIP_TYPE="+getTripType());
		url.append("&");
		url.append("actionURL=http"+URLEncoder.encode("://")+"www.koreanair.com"+URLEncoder.encode("/")+"local"+URLEncoder.encode("/")+"cn"+URLEncoder.encode("/")+"ld"+URLEncoder.encode("/")+"sch"+URLEncoder.encode("/")+"tp"+URLEncoder.encode("/")+"bo"+URLEncoder.encode("/")+"sch_tp_bo_ifr.jsp");
		url.append("&");
		url.append("agentCode=QEC");
		url.append("&");
		url.append("gweb_kal=rkddnjstlr");
		
		return url.toString();
	}
	
	/**
	 * 第五层URL，获取最终数据
	 * @return 
	 */
	public String getLastUrl(String s1,String s2,String s3,String sessionid){
		StringBuffer url=new StringBuffer("https://wftc3.e-travel.com/plnext/KEREG/Fare.action;");
		url.append("jsessionid"+sessionid+"?");
		url.append("0fdffRadioOut=radOut");
		url.append("&");
		url.append("1fdffRadioOut=radOut");
		url.append("&");
		url.append("BANNER=");
		url.append("&");
		url.append("DISPLAY_TYPE=2");
		url.append("&");
		url.append("FLIGHTINBOUND="+s3);
		url.append("&");
		url.append("FLIGHTOUTBOUND="+s2);
		url.append("&");
		url.append("FLIGHT_ID_1="+s2);
		url.append("&");
		url.append("FLIGHT_ID_2="+s3);
		url.append("&");
		url.append("FamilyButton="+s1.replace("|",URLEncoder.encode("|") ));
		url.append("&");
		url.append("IS_DIRTY_INBOUND=Y");
		url.append("&");
		url.append("IS_DIRTY_OUTBOUND=Y");
		url.append("&");
		url.append("LANGUAGE=CN");
		url.append("&");
		url.append("PAGE_TICKET=0");
		url.append("&");
		url.append("PRICING_TYPE=I");
		url.append("&");
		url.append("RECOMMENDATION_ID_1="+s1.split("\\|")[0]);
		url.append("&");
		url.append("SITE=CAUOCAUO");
		url.append("&");
		url.append("SKIN=");
		url.append("&");
		url.append("TRIP_TYPE=R");
		url.append("&");
		url.append("selectSortFlights_out=E");
		
		return url.toString();
	}
	
	
	public Map<String,String> getPa(String s1,String s2,String s3){
		Map<String,String> params=Maps.newHashMap();
		
		params.put("0fdffRadioOut", "radOut");
		params.put("1fdffRadioOut", "");
		params.put("BANNER", "");
		params.put("DISPLAY_TYPE", "2");
		params.put("FLIGHTINBOUND",s3);
		params.put("FLIGHTOUTBOUND", s2);
		params.put("FLIGHT_ID_1", s2);
		params.put("FLIGHT_ID_2",s3);
		params.put("FamilyButton", s1.replace("|",URLEncoder.encode("|") ));
		params.put("IS_DIRTY_INBOUND","Y");
		params.put("IS_DIRTY_OUTBOUND","Y");
		params.put("LANGUAGE","CN");
		params.put("PAGE_TICKET","0");
		params.put("PRICING_TYPE","I");
		params.put("RECOMMENDATION_ID_1",s1.split("\\|")[0]);
		params.put("SITE","CAUOCAUO");
		params.put("TRIP_TYPE","R");
		params.put("LANGUAGE","CN");
		params.put("selectSortFlights_out","E");
		
		return params;
	}
	
	/**
	 * 头等
	 * @return
	*/
	public Map<String,String> getFPa(String s2,String s3){
		Map<String,String> params=Maps.newHashMap();
		
		params.put("CABIN","E");
		params.put("PAGE_TICKET","0");
		params.put("PLTG_SEARCH_RECAP_UPDATED","true");
		params.put("RESTRICTION","true");
		params.put("ROW_1",s2);
		params.put("ROW_2",s3);
		params.put("TRIP_TYPE","R");
		
		return params;
	}
	
	@Override
	public String getUrl() throws Exception {
		return null;
	}

	@Override
	public List<Object> paraseToVo(Object obj) throws Exception {
		switch (super.getRouteType()) {
		case INTERNATIONAL_ROUND:
			return paraseToVoDI(obj);//国际往返
		}
		return null;
	}
	
	
	/**
	 * 国际往返适配器
	 * 
	 */	
	private List<Object> paraseToVoDI(Object fetchObject) throws Exception {
		if(allDatas.size()>0){
			List<AbstractPlaneInfoEntity> list=Lists.newArrayList();
			try{
				
				
			for(Map.Entry<String, Map<String,List<String>>> dataMaps:allDatas.entrySet()){
				String cabinType=dataMaps.getKey();//舱位
				for(Map.Entry<String, List<String>> dataMap:dataMaps.getValue().entrySet()){
					String totalPriceStr="";
					String cabinName="";
					if(priceCanbinName.size()>0){
						totalPriceStr=canbIdPrice.get(dataMap.getKey());//总价
						cabinName=priceCanbinName.get(totalPriceStr);
					}
					List<String>datas=Lists.newArrayList();
					datas=dataMap.getValue();//详细信息
					if(datas.size()>0){
						for(String data:datas){
							//这是一条完整的信息
							DoublePlaneInfoEntity entity=null;
							ReturnDoublePlaneInfoEntity rEntity=null;
							Document doc=Jsoup.parse(data);
							
							//税收，总价，裸价
							String taxPriceStr=doc.select("span[id=taxes_ADT]").first().text().replaceAll("\\)", "");//税价
							 if(priceCanbinName ==null ){
								 totalPriceStr=RegHtmlUtil.regStr(doc.select("span[id=totalForATravellerType_ADT]").first().text().replaceAll(",", ""), "(\\d*\\.00)");//总价
							 }							
							String priceStr=Double.parseDouble(totalPriceStr)-Double.parseDouble(taxPriceStr)+"";
							
							Elements flights=doc.select("table[class=tableFlightConf]");
							if(flights.size()==2){
								for(int j=0;j<flights.size();j++){//分两段，分别为：去，回程
									//去程，或回程段完整信息
									Element flight=flights.get(j);
									List<String> pageL=getPatternList(flight.toString().replace("\n", ""),"(<tr>\\s*<td\\s*class=\"textColorBold\".*?</a>\\W*\\w*</td>\\s*</tr>\\s*</tbody>\\s*</table>\\s*</td>\\s*</tr>)","","");
									if(pageL.size()==1)//没有中转（直达）
									if(pageL.size()>1){//说明有中转
										System.out.println(pageL);
									}
									
									for(int i=0;i<pageL.size();i++){
										//去程，或回程单航段信息
										String fromCityName="",toCityName="",gStartTimeStr="",gEndTimeStr="",rStartTimeStr="",flightNo="",flighType="",company="";
										int gAdd=0,rAdd=0;//出发和到达是否加上天数
										Element grPage=Jsoup.parse(pageL.get(i));
										flighType=grPage.select("td[id^=segAircraft]").text();//飞机类型
										flightNo=RegHtmlUtil.regStr(grPage.select("td[id^=segAirline]").text(), "([A-Z]{2}\\d{1,6})");//航班号
									    if(priceCanbinName ==null ){
									    	cabinName=grPage.select("td[id^=segFareType]").text();//价格类型(商品名)
									    }
										Elements tPage= grPage.select("td[class=textBold]");
										//List<String> tPage=RegHtmlUtil.regStrs(grPage.toString().replace("\n", ""),"(<tr>\\s*?<td\\s*?class=\"textBold\".*?</td>\\s*</tr>)");
										if(tPage.size()==2){//启程，到达信息
											String timeStr="",cityStr="";
											int count=0;
											for(Element oPageE: tPage){
												//去程，或回程段，某一去，或回信息
												String oPage=oPageE.parent().toString();
												timeStr=RegHtmlUtil.regStr(oPage,"(\\d{1,2}:\\d{1,2})");//出发，到达时间
												count=RegHtmlUtil.regStr(oPage,"\\+(.*)\\s*\\天")==null?0:Integer.parseInt(RegHtmlUtil.regStr(oPage,"\\+(.*)\\s*\\天").replaceAll(" ", ""));//+xx天
												cityStr=oPageE.parent().getElementsByTag("td").last().text().split("\\,")[0];//RegHtmlUtil.regStr(oPage,"<td\\s*?(\\w*)\\,");//出发，到达城市名
											
												if(oPage.contains("启程")){//启程信息
													gStartTimeStr=timeStr;
													gAdd=count;
													fromCityName=cityStr;
												}
												if(oPage.contains("到达")){//到达信息
													toCityName=cityStr;
													gEndTimeStr=timeStr;
													rAdd=count;
												}
											}
											
											
											
											if(j==0 ){//去程信息
												if(i==0){//去程第一趟
													//去程大实体
													CabinEntity cabinEntity=new CabinEntity();//去程舱位信息
													entity=PlaneInfoEntityBuilder.buildPlaneInfo(
															taskQueue, "KE", "大韩航空", "大韩航空公司",getDateStr(gAdd,taskQueue.getFlightDate(),gStartTimeStr),null, flightNo, priceStr, null, priceStr, flighType, DoublePlaneInfoEntity.class);
													cabinEntity.setCabinType(cabins.get(cabinType));
													cabinEntity.setProductName(cabinName);
													entity.getCabins().add(cabinEntity);
												}
												if(i==pageL.size()-1){//去程最后一趟
													entity.setEndTime(DateUtil.string2Date(getDateStr(rAdd,taskQueue.getFlightDate(),gEndTimeStr), "yyyy-MM-dd HH:mm:ss"));
												}
												if(pageL.size()>1){//去程中转
													TransitEntity trEntity=PlaneInfoEntityBuilder.buildTransitEntity(
															flightNo, flightNo, "KE", "大韩航空", "大韩航空公司", null, fromCityName,null, toCityName,flighType,TransitEntity.class);
													entity.getTransits().add(trEntity);
												}
											}
											
											
											if(j==1){//回程信息
												if(i==0){//回程第一趟
													rEntity=PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, "KE","大韩航空", "大韩航空公司", getDateStr(gAdd,taskQueue.getReturnGrabDate(),gStartTimeStr), null, flightNo, priceStr, null, priceStr, flighType,ReturnDoublePlaneInfoEntity.class);
													ReturnCabinEntity reEn=new ReturnCabinEntity();//去程舱位信息
													reEn.setCabinType(cabins.get(cabinType));
													reEn.setProductName(cabinName);//商品名
													rEntity.getReturnCabins().add(reEn);
												}
												if(i==pageL.size()-1 ){//回程最后一趟
													rEntity.setEndTime(DateUtil.string2Date(getDateStr(rAdd,taskQueue.getReturnGrabDate(),gEndTimeStr), "yyyy-MM-dd HH:mm:ss"));
												}
												if(pageL.size()>1){//回程中转
													ReturnTransitEntity rTr=PlaneInfoEntityBuilder.buildTransitEntity(
															flightNo, flightNo,"KE", "大韩航空", "大韩航空公司",fromCityName, null, toCityName, null, null,ReturnTransitEntity.class);
													rEntity.getReturnTransits().add(rTr);
												}
												
												
											}
										}
									}
								}
								if(rEntity.getReturnTransits().size()>0){
									rEntity.setSumHighestPrice(Double.parseDouble(totalPriceStr));
									rEntity.setSumLowestPrice(Double.parseDouble(totalPriceStr));
									rEntity.setTotalHighestTaxesPrice(Double.parseDouble(priceStr));
									rEntity.setTotalLowestTaxesPrice(Double.parseDouble(priceStr));
									entity.getReturnPlaneInfos().add(rEntity);
								}
								//把价格set入实体
								entity.setSumHighestPrice(Double.parseDouble(totalPriceStr));
								entity.setSumLowestPrice(Double.parseDouble(totalPriceStr));
								entity.setTotalHighestTaxesPrice(Double.parseDouble(priceStr));
								entity.setTotalLowestTaxesPrice(Double.parseDouble(priceStr));
								list.add(entity);					
							}else{
								throw new MessageException(String.format("【%s】航段有误", flights.size()));
							}
						}
					}
				}
			  }
			}catch (Exception e) {
				e.printStackTrace();
			}
			return Arrays.asList(list.toArray());
		}else return null;
		
	}

	/**
	 * 处理日期格式\
	 * @return 
	 */
	
	public String getDateStr(int i,String flightDate,String timeStr){
		String dateStr="";
		if(flightDate !=null && !flightDate.equals("") && timeStr !=null && !timeStr.equals("") ){
			
			try {
				flightDate=DateUtil.addDays("yyyy-MM-dd",flightDate, i);
				dateStr=flightDate+" "+timeStr+":00";
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			
		}
		
		return dateStr;
	}
	
	
	@Override
	public boolean validateFetch(Object arg0) throws Exception {
		return false;
	}
	
	/**
	 * 获取单程还是往返
	 * @return
	 */
	private String getTripType(){
		if(taskQueue.getIsReturn() == 0){
			return "O";
		}else{
			return "R";
		}
	}
	
	/**
	 * 获取请求日期的格式
	 * @return
	 */

	private String getRequestDate(String date){
		return date.replaceAll("\\D", "") + "0000";
	}

}
